package com.xhapi.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.xhapi.pojo.dto.handwrite.Block;
import com.xhapi.pojo.dto.handwrite.OuterDto;
import com.xhapi.service.OCRService;
import com.xhapi.utils.FileUtil;
import com.xhapi.utils.HttpUtil;
import com.xhapi.utils.ocrUtils.textIn.JsonResponse;
import com.xhapi.utils.ocrUtils.textIn.WenZiApi;
import com.xhapi.utils.ocrUtils.xhOCR.HandWrite;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.xhapi.utils.ocrUtils.xhOCR.HandWrite.WEBOCR_URL;

@RequiredArgsConstructor
@Service
@Slf4j
public class OCRServiceImpl implements OCRService {
    private final WenZiApi wenZiApi;
    private final HandWrite handWrite;

    @Override
    public String picToText(byte[] bytes) {
        try {
            String json = wenZiApi.WenZiApi(bytes);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonResponse response = objectMapper.readValue(json, JsonResponse.class);
            StringBuilder res = new StringBuilder();
            String texts = "";
            for (JsonResponse.Result.Line line : response.getResult().getLines()) {
                texts += line.getText();
            }
            log.info(texts);
            return texts;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String picToTextByHandWrite(String path) {
        try {
            log.info(path);
            Map<String, String> header = handWrite.constructHeader("cn|en", "false");
            // 读取图像文件，转二进制数组，然后Base64编码
            byte[] imageByteArray = FileUtil.read2ByteArray(path);
            String imageBase64 = new String(Base64.encodeBase64(imageByteArray), "UTF-8");
            String bodyParam = "image=" + imageBase64;
            String result = HttpUtil.doPost(WEBOCR_URL, header, bodyParam);

            ObjectMapper objectMapper = new ObjectMapper();
            OuterDto outerDto = null;
            try {
                outerDto = objectMapper.readValue(result, OuterDto.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            String code = outerDto.getCode();
            System.out.println("Code: " + code);
            StringBuilder stringBuilder = new StringBuilder();
            for (Block block : outerDto.getData().getBlock()) {
                for (Block.Line line : block.getLine()) {
                    for (Block.Line.Word word : line.getWord()) {
                        stringBuilder.append(word.getContent());
                        stringBuilder.append(" ");// Extract all contents
                    }
                }
            }
            System.out.println(stringBuilder);
            return stringBuilder.toString();

        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
